﻿using Autofac;
using Oxygen.Mesh.Dapr;
using RpcInterface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ServiceSample
{
    public class ProductService : BaseActorService<ProductPo>, IProductService
    {
        static int visitCount = 0;
        public async Task<ProductOutput> Get(ProductInput input)
        {
            ActorData ??= new ProductPo() { Id = 1, Name = "小白菜", Stock = 100 };
            Console.WriteLine($"第{visitCount}次Get请求成功，当前库存剩余{ActorData.Stock}");
            return await Task.FromResult(new ProductOutput() { Message = $"第{visitCount}次请求成功，当前库存剩余{ActorData.Stock}" });
        }

        public async Task<ProductOutput> ReduceStock(ProductInput input)
        {
            Interlocked.Increment(ref visitCount);
            // await Task.Delay(new Random(Guid.NewGuid().GetHashCode()).Next(20, 50));// 模拟数据库耗时
            if (ActorData.Stock >= input.ReduceStock)
            {
                // await Task.Delay(new Random(Guid.NewGuid().GetHashCode()).Next(50, 100));// 模拟数据库耗时
                ActorData.Stock -= input.ReduceStock;
            }
            Console.WriteLine($"第{visitCount}次ReduceStock请求成功，当前库存剩余{ActorData.Stock}");
            return new ProductOutput() { Message = $"第{visitCount}次请求成功，当前库存剩余{ActorData.Stock}" };
        }

        public async override Task SaveData(ProductPo model, ILifetimeScope scope)
        {
            Console.WriteLine("同步请求被调用了，此处可以进行数据库持久化！");
            await Task.CompletedTask;
        }
    }
}
